package com.example.forum.services.impl;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.dao.BoardMapper;
import com.example.forum.dao.MessageMapper;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private ArticleMapper articleMapper;
    
    @Autowired
    private BoardMapper boardMapper;
    
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ArticleReplyMapper articleReplyMapper;

    @Override
    public void createNormalUser(User user) {
        //1.非空校验
        if(user==null|| StringUtil.isEmpty(user.getUsername())||
        StringUtil.isEmpty(user.getNickname())||StringUtil.isEmpty(user.getPassword())||
        StringUtil.isEmpty(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.查询用户名 是否存在
        User existsUser=userMapper.selectByUsername(user.getUsername());
        //如果查到说明用户存在
        if(existsUser!=null){
            //打印日志
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //校验通过 新增用户  设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //当前日期
        Date data=new Date();
        user.setCreateTime(data);
        user.setUpdateTime(data);
        //写入数据库
        int res=userMapper.insertSelective(user);
        //如果影响行数不为1 说明插入失败
        if(res!=1){
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //操作成功 打印日志
        log.info("新增成功 username = "+user.getUsername()+ " . ");
        //打印结果
        System.out.println(user);
    }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if(StringUtil.isEmpty(username)){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUsername(username);
    }

    @Override
    public User selectByUsername(String username) {
        //非空校验
        if(StringUtil.isEmpty(username)){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUsername(username);
    }

    @Override
    public User login(String username, String password) {
        //1.非空校验
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据用户名查询用户
        User user=selectByUserName(username);
        //3.对查询结果做非空校验
        if(user==null||user.getId()<=0){
            log.warn(ResultCode.FAILED_LOGIN.toString()+"user = "+username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4.对密码进行校验
        String encryptPassword= MD5Util.md5Salt(password,user.getSalt());
        //密码错误 equalsIgnoreCase 比较 排除大小写
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString()+" 密码错误,password = "+password);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //校验通过 返回用户信息
        log.info("登录成功 username= "+ username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        //参数校验
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao 获取查询对象
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id<=0||id==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询原来的板块的数量
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", board id= "+id);
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        //对其进行+1
        updateUser.setArticleCount(user.getArticleCount()+1);
        //调用执行
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数!=1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id<=0||id==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询原来的板块的数量
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", board id= "+id);
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        //对其进行+1
        if(user.getArticleCount()<=0){
            updateUser.setArticleCount(0);
        }else {
            updateUser.setArticleCount(user.getArticleCount()-1);
        }
        //调用执行
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数!=1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void addOneCommentCountById(Long id) {
        if(id<=0||id==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询原来的用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", user id= "+id);
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        //对评论数进行+1，如果为null则设置为1
        updateUser.setCommentCount(user.getCommentCount() == null ? 1 : user.getCommentCount()+1);
        //调用执行
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数!=1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneCommentCountById(Long id) {
        if(id<=0||id==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询原来的用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", user id= "+id);
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        //对评论数进行-1，如果小于等于0则设置为0
        if(user.getCommentCount() == null || user.getCommentCount()<=0){
            updateUser.setCommentCount(0);
        }else {
            updateUser.setCommentCount(user.getCommentCount()-1);
        }
        //调用执行
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数!=1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void addOneLikeCountById(Long id) {
        if(id<=0||id==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询原来的用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", user id= "+id);
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        //对点赞数进行+1，如果为null则设置为1
        updateUser.setLikeCount(user.getLikeCount() == null ? 1 : user.getLikeCount()+1);
        //调用执行
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数!=1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneLikeCountById(Long id) {
        if(id<=0||id==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询原来的用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+", user id= "+id);
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        //对点赞数进行-1，如果小于等于0则设置为0
        if(user.getLikeCount() == null || user.getLikeCount()<=0){
            updateUser.setLikeCount(0);
        }else {
            updateUser.setLikeCount(user.getLikeCount()-1);
        }
        //调用执行
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响的行数!=1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //校验参数
        if(user==null||user.getId()<=0||user.getId()==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User existsUser=userMapper.selectByPrimaryKey(user.getId());
        if(existsUser==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义一个标志位 用于判断所有属性是否为空
        //如果有一个校验通过 就赋值为true 最后判断其是否为false 如果是false 表示所有属性都为空
        //就可以直接抛出异常
        boolean checkAttr=false;
        User updateUser =new User();
        updateUser.setId(user.getId());
        //校验用户名
        if(!StringUtil.isEmpty(user.getUsername())&&
        !user.getUsername().equals(existsUser.getUsername())){
            //对用户名进行唯一性校验
            User checkUser=userMapper.selectByUsername(user.getUsername());
            if(checkUser!=null){
                //如果查询到了 说明用户名已经存在了 抛出异常
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            //如果不存在 就设置属性
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr=true;
        }
        //校验昵称
        if(!StringUtil.isEmpty(user.getNickname())&&!user.getNickname().equals(existsUser.getNickname())){
            //校验通过 设置属性 设置标志位置
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }
        //校验性别
        if(user.getGender()!=null&&user.getGender()!=existsUser.getGender()){
            updateUser.setGender(user.getGender());
            //校验合法性
            if(updateUser.getGender()>2||updateUser.getGender()<0){
                //如果不合法  设置为默认值2
                updateUser.setGender((byte) 2);
            }
            checkAttr=true;
        }
        //校验邮箱
        if(!StringUtil.isEmpty(user.getEmail())&&!user.getEmail().equals(existsUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }
        //校验电话号码
        if(!StringUtil.isEmpty(user.getPhoneNum())&&!user.getPhoneNum().equals(existsUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }
        //校验个人简介
        if(!StringUtil.isEmpty(user.getRemark())&&!user.getRemark().equals(existsUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }
        //根据标志位来决定是否更新
        if(checkAttr==false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //全部校验通过 执行操作
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+"数据库受影响行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if(id==null||id<=0||StringUtil.isEmpty(newPassword)||StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取当前用户 校验原密码是否正确
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null||user.getId()<=0||user.getDeleteState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验原密码是否正确 进行加密操作
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if(!oldEncryptPassword.equals(user.getPassword())){
            //密码校验失败 抛出异常
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //原密码正确 执行修改操作 对新密码进行加密
        String salt= UUIDUtils.UUID_32();
        String encryptPassword=MD5Util.md5Salt(newPassword,salt);
        //执行修改密码操作 构造对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString()+"数据库受影响行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public List<User> getAllUsers() {
        // 查询所有未删除的用户
        return userMapper.selectAllUsers();
    }
    
    @Override
    public void updateUserState(Long userId, Byte state) {
        // 参数校验
        if (userId == null || userId <= 0 || (state != 0 && state != 1)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(userId);
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 创建更新对象
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setState(state);
        updateUser.setUpdateTime(new Date());
        
        // 执行更新
        int result = userMapper.updateByPrimaryKeySelective(updateUser);
        if (result != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 用户状态更新失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        
        log.info("用户状态已更新，userId={}, state={}", userId, state);
    }
    
    @Override
    public void deleteUser(Long userId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(userId);
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 创建更新对象（逻辑删除）
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setDeleteState((byte) 1);
        updateUser.setUpdateTime(new Date());
        
        // 执行更新
        int result = userMapper.updateByPrimaryKeySelective(updateUser);
        if (result != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 用户删除失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        
        log.info("用户已删除（逻辑删除），userId={}", userId);
    }
    
    @Override
    public void updateUserAdmin(Long userId, Byte isAdmin) {
        // 参数校验
        if (userId == null || userId <= 0 || (isAdmin != 0 && isAdmin != 1)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(userId);
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 创建更新对象
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setIsAdmin(isAdmin);
        updateUser.setUpdateTime(new Date());
        
        // 执行更新
        int result = userMapper.updateByPrimaryKeySelective(updateUser);
        if (result != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 用户管理员权限更新失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        
        log.info("用户管理员权限已更新，userId={}, isAdmin={}", userId, isAdmin);
    }
    
    @Override
    public void updateUserByAdmin(User user) {
        // 参数校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 确保更新时间不为空
        if (user.getUpdateTime() == null) {
            user.setUpdateTime(new Date());
        }
        
        // 执行更新
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 管理员更新用户信息失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        
        log.info("管理员已更新用户信息，userId={}", user.getId());
    }
    
    @Override
    public List<User> getActiveUsers(int limit) {
        // 参数校验
        if (limit <= 0) {
            limit = 5; // 默认返回5个活跃用户
        }
        
        // 调用数据访问层获取活跃用户
        return userMapper.selectActiveUsers(limit);
    }
    
    /**
     * 获取系统统计数据
     * @return 系统统计数据Map
     */
    public Map<String, Object> getSystemStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 统计用户数
        stats.put("totalUsers", userMapper.countTotalUsers());
        stats.put("todayNewUsers", userMapper.countTodayNewUsers());
        
        // 统计文章数
        stats.put("totalArticles", articleMapper.countTotalArticles());
        stats.put("todayNewArticles", articleMapper.countTodayNewArticles());
        
        // 统计评论数（使用新的方法，只统计关联到未删除文章的评论）
        try {
            stats.put("totalComments", articleReplyMapper.countTotalReplies());
            stats.put("todayNewComments", articleReplyMapper.countTodayNewReplies());
        } catch (Exception e) {
            log.error("获取评论统计数据出错", e);
            // 出错时使用消息系统的统计数据作为后备
            stats.put("totalComments", messageMapper.countTotalMessages());
            stats.put("todayNewComments", messageMapper.countTodayNewMessages());
        }
        
        // 统计访问量（从文章的访问次数总和获取）
        try {
            Integer totalVisits = articleMapper.countTotalVisits();
            stats.put("totalVisits", totalVisits != null ? totalVisits : 0);
        } catch (Exception e) {
            log.error("获取访问量统计出错", e);
            stats.put("totalVisits", 0);
        }
        
        return stats;
    }
    
    @Override
    public int countTotalUsers() {
        return userMapper.countTotalUsers();
    }
    
    @Override
    public int countTodayNewUsers() {
        return userMapper.countTodayNewUsers();
    }

    @Override
    public Map<String, Object> getUserStats(Long userId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        Map<String, Object> stats = new HashMap<>();
        
        // 获取评论数 - 通过查询文章回复表
        Integer commentCount = articleMapper.countUserComments(userId);
        stats.put("commentCount", commentCount != null ? commentCount : 0);
        
        // 获取获赞数 - 通过查询文章表中该用户文章的总点赞数
        Integer likeCount = articleMapper.countUserLikes(userId);
        stats.put("likeCount", likeCount != null ? likeCount : 0);
        
        return stats;
    }
    
    @Override
    public Map<String, Object> getUsersByPage(int page, int size, String sort, String order) {
        // 参数校验
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        
        // 验证排序字段
        List<String> validSortFields = Arrays.asList("id", "username", "nickname", "createTime", "updateTime");
        if (!validSortFields.contains(sort)) {
            sort = "createTime"; // 默认按创建时间排序
        }
        
        // 验证排序方向
        if (!"asc".equalsIgnoreCase(order) && !"desc".equalsIgnoreCase(order)) {
            order = "desc"; // 默认降序
        }
        
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 查询分页数据
        List<User> users = userMapper.selectUsersByPage(offset, size, sort, order);
        
        // 查询总记录数
        int total = userMapper.countUsersByCondition();
        
        // 组装结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", users);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        
        return result;
    }
    
    /**
     * 根据用户ID获取用户基本信息
     * @param userId 用户ID
     * @return 包含用户基本信息的Map
     */
    @Override
    public Map<String, Object> selectUserInfoById(Long userId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取用户信息
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return null;
        }
        
        // 组装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getId());
        result.put("username", user.getUsername());
        result.put("nickname", user.getNickname());
        result.put("avatarUrl", user.getAvatarUrl());
        result.put("gender", user.getGender());
        result.put("email", user.getEmail());
        result.put("phoneNum", user.getPhoneNum());
        result.put("articleCount", user.getArticleCount());
        result.put("commentCount", user.getCommentCount());
        result.put("likeCount", user.getLikeCount());
        result.put("createTime", user.getCreateTime());
        
        return result;
    }

    /**
     * 创建用户（管理员功能）
     * @param user 用户实体
     */
    @Override
    public void createUser(User user) {
        // 设置初始统计数据
        user.setArticleCount(0);
        user.setCommentCount(0);
        user.setLikeCount(0);
        
        // 如果未设置性别，默认为未知(2)
        if (user.getGender() == null) {
            user.setGender((byte) 2); // 0男，1女，2未知
        }
        
        // 如果未设置管理员权限，默认为普通用户
        if (user.getIsAdmin() == null) {
            user.setIsAdmin((byte) 0); // 0 普通用户
        }
        
        // 如果未设置状态，默认为正常
        if (user.getState() == null) {
            user.setState((byte) 0); // 0 正常
        }
        
        // 设置删除状态为未删除
        user.setDeleteState((byte) 0);
        
        // 如果未设置创建时间，设置为当前时间
        if (user.getCreateTime() == null) {
            user.setCreateTime(new Date());
        }
        
        // 如果未设置更新时间，设置为当前时间
        if (user.getUpdateTime() == null) {
            user.setUpdateTime(new Date());
        }
        
        userMapper.insert(user);
    }
}
